<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Currency extends AdminBase {
	public function __construct()
    {
        parent::__construct();
    }

	public function index()
	{
		$post = $this->input->post();
		if($post){
			if(isset($post['id'])){//name order 
				if(isset($post['name'])){//修改名称
					$this->db->where('id',$post['id']);
					$this->db->update('currency',$post);
					$this->output->set_content_type('application/json')
					 ->set_output(json_encode(array('statu' => 'ok','message'=>'修改成功！')));
					return;
				}else{
					if(isset($post['order'])){//排序
						$this->db->where('id',$post['id']);
						$this->db->update('currency',['order'=>$post['order']]);
						$this->output->set_content_type('application/json')
						 ->set_output(json_encode(array('statu' => 'ok','message'=>'排序成功！')));
						return;
					}else{//删除  检查是否有属于该语言的商品
						$location = $this->db->get_where('location',['currency_id'=>$post['id']])->row_array();
						if($location){
							$this->output->set_content_type('application/json')
							 ->set_output(json_encode(array('statu' => 'failed','message'=>'删除失败，请先修改或删除属于该货币的地区！')));
							return;
						}elseif($this->db->count_all('currency')==1){
							$this->output->set_content_type('application/json')
							 ->set_output(json_encode(array('statu' => 'failed','message'=>'删除失败，至少保留一种货币！')));
							return;
						}else{
							$this->db->delete('currency', array('id' => $post['id']));
							$this->output->set_content_type('application/json')
							 ->set_output(json_encode(array('statu' => 'ok','message'=>'删除成功！')));
							return;
						}
					}
				}
			}else{ //新增
				$this->db->select('order');
				$this->db->order_by('order', 'DESC');
				$max = $this->db->get('currency')->row_array();
				$post['order'] = $max?$max['order']+1:0;
				$this->db->insert('currency',$post);
				$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'新增成功！')));
				return;
			}
		}else{
			$this->db->order_by('order','ASC');
	        $currency = $this->db->get('currency')->result_array();
			$this->admin_view('currency_list','货币管理',array('list'=>$currency));
		}


        
	}
}
